// Controller/websocket.js

const  RealtimeData  = require('../models/RealtimeData');

// 处理WebSocket消息的函数
async function handleWebSocketMessage(ws, message) {
  const messageString = message.toString();
  if (messageString === '1') {
    try {
      // 查询数据库中的数据
      const dataCursor = await RealtimeData.findAll({ order: [['ID', 'ASC']], raw: true });
      
      // 遍历查询结果并逐条发送给客户端
      for (const data of dataCursor) {
        ws.send(JSON.stringify(data));
        await new Promise((resolve) => setTimeout(resolve, 1000)); // 间隔一秒发送下一条数据
      }
    } catch (error) {
      console.error('Error sending data:', error);
    }
  }
}

module.exports = {
  handleWebSocketMessage,
};
